package com.ym521.activitystack

import android.app.Application
import android.content.Context
import android.content.Intent
import androidx.annotation.MainThread
import androidx.fragment.app.FragmentActivity
import com.ym521.activitystack.core.foreground.AppSateManager
import com.ym521.activitystack.core.foreground.AppSateManagerImpl

/**
 * @author Ym
 * @Email 2435970206@qq.com
 * @QQ 2435970206
 * Android activityStack 辅助类
 * 也是使用的核心类
 * 且是单例
 */
object YmActivityStack : YmActivityStackUse {
    private var sateManager: AppSateManager? = null

    /**
     * 初始化
     * 重复初始化 只有第一次有效
     */
    @MainThread
    override fun init(application: Application) {
        if (sateManager == null)
            sateManager = AppSateManagerImpl
                .builder()
                .registerActivityCallbacks(application)
    }

    /**
     * 获取当前 栈顶Activity
     */
    override fun currentActivity(): FragmentActivity {
        sateManager?.let {
            return it.activityStackManager.current()
        }
        throw RuntimeException("请先初始化 ActivityStackHelper， 先调用init函数")
    }

    /**
     * 回退当前栈顶Activity
     */
    override fun popActivity() {
        sateManager?.let {
            return it.activityStackManager.pop()
        }
        throw RuntimeException("请先初始化 ActivityStackHelper， 先调用init函数")
    }

    /**
     * 回退并销毁指定的Activity或者
     */
    override fun popActivity(activity: FragmentActivity) {
        sateManager?.let {
            return it.activityStackManager.pop(activity)
        }
        throw RuntimeException("请先初始化 ActivityStackHelper， 先调用init函数")
    }

    override fun <T : FragmentActivity> popActivity(clazz: Class<T>) {
        sateManager?.let {
            return it.activityStackManager.pop(clazz)
        }
        throw RuntimeException("请先初始化 ActivityStackHelper， 先调用init函数")
    }

    override fun popAllActivity() {
        sateManager?.let {
            return it.activityStackManager.popAll()
        }
        throw RuntimeException("请先初始化 ActivityStackHelper， 先调用init函数")
    }

    /**
     * 判断APP 当前是否在前台运行
     * @return true 是在前台运行，false 是在后台运行
     */
    override fun isForeground(): Boolean {
        sateManager?.let {
            return it.isForeground()
        }

        throw RuntimeException("请先初始化 ActivityStackHelper， 先调用init函数")
    }

    /**
     * 重启APP
     */
    override fun restartApp(mContext: Context) {
        val intent = mContext.packageManager.getLaunchIntentForPackage(mContext.packageName)
        intent?.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        mContext.startActivity(intent)
        Runtime.getRuntime().exit(0)
    }


}